﻿/*!
* Ext JS Library 3.1.1
* Copyright(c) 2006-2010 Ext JS, LLC
* licensing@extjs.com
* http://www.extjs.com/license
*/
Ext.onReady(function () {
    Ext.QuickTips.init();
    Ext.form.Field.prototype.msgTarget = 'side';

    var paymentId = $("#paymentId").attr('value');
    var cardNumber = $('#cardNumber').attr('value');

    /*Functions

    */
    function getAction(action) {
        var result = '';
        switch (action) {
            case 'add':
                result = '/AutoPayments/Create';
                break;
            case 'update':
                result = '/AutoPayments/Update';
                break;
            case 'delete':
                result = '/AutoPayments/Delete';
                break;
        }
        return result;
    }

    function fillRequiredFields(form) {
        form.add({
            fieldLabel: "Currency",
            name: "currency",
            editable: false,
            triggerAction: 'all',
            allowBlank: false,
            mode: 'local',
            xtype: "combo",
            store: new Ext.data.ArrayStore({
                id: 0,
                fields: [
                                            'myId',
                                            'displayText'
                                        ],
                data: [['BYR', 'BYR'], ['USD', 'USD']]
            }),
            valueField: 'myId',
            displayField: 'displayText'
        });
        form.add({
            fieldLabel: "Amount",
            name: "amount",
            allowBlank: false,
            xtype: "numberfield",
            value: 0,
            minValue: 1,
            maxValue: 1000000000
        });
        form.add({
            fieldLabel: "Day of month",
            name: "dayOfMonth",
            allowBlank: false,
            xtype: "numberfield",
            minValue: 0,
            maxValue: 59,
            value: 0
        });
        form.add({
            hidden: true,
            id: 'paymentDetail',
            name: "paymentDetail",
            value: 0
        });
    }
    function fillForm(form, data) {

        removeElementsFromForm(form);
        for (var i = 0; i < data.length; i++) {
            var record = data[i];
            if (record.name != 'amount' && record.name != 'dayOfMonth' && record.name != 'paymentDetail' && record.name != 'currency') {
                record.regexfromServer = record.regex;
                record.regex = new RegExp(record.regex);

                form.add(record);
            }
        }
        fillRequiredFields(form);
    }
    function fillFormForUpdate(form, data) {
        removeElementsFromForm(form);
        var fields = data.detail;
        for (var i = 0; i < fields.length; i++) {
            var record = fields[i];
            if (record.name != 'amount' && record.name != 'dayOfMonth' && record.name != 'paymentDetail' && record.name != 'currency') {
                record.regex = new RegExp(record.regex);
                form.add(record);
            }
        }
        form.add({
            fieldLabel: "Currency",
            name: "currency",
            editable: false,
            triggerAction: 'all',
            allowBlank: false,
            mode: 'local',
            xtype: "combo",
            value: data.currency,
            store: new Ext.data.ArrayStore({
                id: 0,
                fields: [
                                            'myId',
                                            'displayText'
                                        ],
                data: [['BYR', 'BYR'], ['USD', 'USD']]
            }),
            valueField: 'myId',
            displayField: 'displayText'
        });
        form.add({
            fieldLabel: "Amount",
            name: "amount",
            allowBlank: false,
            xtype: "numberfield",
            value: data.amount,
            minValue: 1,
            maxValue: 1000000000
        });
        form.add({
                hidden: true,
//            fieldLabel: "Day of month",
            name: "dayOfMonth",
            allowBlank: false,
            xtype: "numberfield",
            value: data.dayOfMonth,
            minValue: 0,
            maxValue: 59
        });
        form.add({
            hidden: true,
            id: 'paymentDetail',
            name: "paymentDetail",
            value: 0
        });
    }

    /*Components
    */

    // create the Data Store for a grid
    var store = new Ext.data.JsonStore({
        root: 'topics',
        totalProperty: 'totalCount',
        idProperty: 'Id',
        remoteSort: true,
        baseParams: {
            'cardNumber': cardNumber,
            'paymentId': paymentId
        },
        fields: [
                'Id', 'Number', 'Amount', 'DayOfMonth', 'ISO'
            ],

        proxy: new Ext.data.HttpProxy({
            method: 'POST',
            url: '/AutoPayments/MaintenanceJSON'

        })
    });
    store.setDefaultSort('lastpost', 'desc');



    var simple = new Ext.FormPanel({
        border: false,
        labelWidth: 140, // label settings here cascade unless overridden
        url: getAction('add'),
        frame: true,
        header: false,
        autoScroll: true,
        title: 'Simple Form',
        bodyStyle: 'padding:5px 5px 0',

        width: 350,
        defaults: { width: 230 },
        defaultType: 'textfield',


        buttons: [{
            iconCls: 'icon-save',
            text: 'Save',
            listeners: {
                click: function () {
                    var res = saveData(simple);
                    $('#paymentDetail').attr('value', res);

                    var form = simple.getForm();

                    if (form.isValid()) {
                        wnd.hide();
                        var row = grid.getSelectionModel().getSelected();
                        var id = (row) ? row.get('Id') : '';
                        form.submit({
                            url: simple.url,
                            params: { 'autoPaymentId': id },
                            success: function (form, action) {
                                store.load();
                            },
                            failure: function (form, action) {
                                Ext.Msg.alert('Failed', action.result ? action.result.message : 'No response');
                            }
                        });
                    }

                }
            }
        }, {
            text: 'Cancel',
            listeners: {
                click: function () { wnd.hide(); }
            }
        }]
    });



    var wnd = new Ext.Window({
        title: 'Add autopayment',
        closable: true,
        width: 600,
        height: 350,
        autoScroll: true,
        closeAction: 'hide',
        //border:false,
        // plain: true,
        layout: 'fit',
        items: [simple]
    });


    var grid = new Ext.grid.GridPanel({
        //  width: 400,
        height: 500,
        title: 'Autopaymets List',
        store: store,
        trackMouseOver: false,
        // disableSelection: true,
        loadMask: true,
        sm: new Ext.grid.RowSelectionModel({ singleSelect: true }),
        // grid columns
        columns: [
            {
                id: 'Id', // id assigned so we can apply custom css (e.g. .x-grid-col-topic b { color:#333 })
                header: "Id",
                dataIndex: 'Id',
                hidden: true,
                sortable: true
            },
            {
                header: "#",
                dataIndex: "Number",
                width: 20
            },
         {
             header: "$",
             dataIndex: 'Amount',
             width: 40,
             sortable: true
         },
             {
                 header: "Currency",
                 dataIndex: 'ISO',
                 width: 40,
                 sortable: true
             }, {
                 header: "Day Of Month",
                 dataIndex: 'DayOfMonth',
                 //width: 'auto',
                 align: 'right',
                 sortable: true
             }],
        listeners: {
            rowclick: function (gird, index, rec) {
                var row = grid.getSelectionModel().getSelected();
                if (row) {
                    var autoPaymentId = row.get('Id');
                    $('#autoPaymentId').attr('value', autoPaymentId);
                }
            }
        },
        buttons: [
            {
                text: 'Add',
                iconCls: 'silk-add',
                listeners: {
                    click: function () {

                        if (wnd.hidden) {
                            wnd.setTitle('Add AutoPayment');
                            $.post('/Payments/DetailJSON', { id: paymentId, cardNumber: cardNumber }, function (data, resp, text) {
                                fillForm(simple, data);
                                simple.url = getAction('add');
                                wnd.show(this);
                            });
                        }
                    }
                }
            },

            { text: 'Edit',
                iconCls: 'icon-edit',
                listeners: {
                    click: function () {

                        if (wnd.hidden) {
                            wnd.setTitle('Edit AutoPayment');
                            simple.url = getAction('update');
                            var row = grid.getSelectionModel().getSelected();
                            if (row) {
                                var autoPaymentId = row.get('Id');

                                $.post('/AutoPayments/Load', { autoPaymentId: autoPaymentId }, function (data, resp, text) {
                                    // var data = eval(data);
                                    fillFormForUpdate(simple, data);

                                    wnd.show(this);
                                });

                            }
                        }
                    }
                }
            },
            { text: 'Delete',
                iconCls: 'icon-delete',
                listeners: {

                    click: function () {

                        var row = grid.getSelectionModel().getSelected();
                        if (row) {
                            var id = row.get('Id');
                            Ext.MessageBox.confirm('Confirm', 'Are you sure you want to do that?',
                                 function (btn, text) {
                                     if (btn == 'yes') {
                                         $.post('/AutoPayments/Delete', { autoPaymentId: row.get('Id') }, function (data, resp, text) {
                                             store.load();
                                         });
                                     }
                                 }
                            );

                        }
                    }
                }
            }],

        // paging bar on the bottom
        bbar: new Ext.PagingToolbar({
            pageSize: 1,
            store: store,
            displayInfo: true,
            displayMsg: 'Displaying autopayments {0} - {1} of {2}',
            emptyMsg: "No autopayments to display",
            items: [
                '-'
           ]
        })
    });

    // render it
    grid.render('grid-example');

    // trigger the data store load
    store.load({ params: { start: 0} });
});